import socket
import threading
from data_processing.client_thread_handle import ClientThreadHandle

IP = "127.0.0.1"
Port = 19901
server_address = IP, Port


class TcpServer(object):
    def __init__(self, address):
        self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 定义套接字类型
        self.tcp_socket.bind(address)  # 绑定端口
        self.client_dict = {}
        self.run()

    def run(self) -> None:
        self.tcp_socket.listen(20)  # 开始监听客户的连接
        print("已开启TCP Server，正在监听客户端连接")
        while True:
            conn, address = self.tcp_socket.accept()  # 获取连接的客户AA端
            client_key = address[0] + ":" + str(address[1])
            print(client_key, " 已连接.......")
            self.client_dict[client_key] = threading.Thread(target=self.handle, args=(conn,))
            self.client_dict[client_key].start()

    @staticmethod
    def handle(conn: socket.socket):
        b = ClientThreadHandle(conn, "7E")
        b.run()


# 开始监听客户的连接


if __name__ == '__main__':
    TcpServer(server_address)
